<?php


namespace app\common\business;


use app\common\lib\PushMessage;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\PatientInfo;

use app\common\model\TimingTask;
use catchAdmin\visitPlan\model\VisitPlan;
use catchAdmin\visitPlan\model\VisitPlanDetail;
use MongoDB\BSON\ObjectId;

class VisitPlanSend
{
    public function sendVisitByVisitId(string $visitId): bool
    {
        try {

            # 根据data下的复诊计划id获取复诊计划详情
            $visitInfo = (new VisitPlan())->find($visitId);

            if (empty($visitInfo)) {
                return true;
            }
            //获取所有患者的手机号并且过滤终止的患者
            $patientList = (new VisitPlanDetail())->where([["visit_id", "=", $visitId], ["status", ">", -1], ["is_stop", "=", 0]])->select();
            if (empty($patientList)) {
                return true;
            }
            foreach ($patientList as $k => $v) {
                //判断患者是否死亡
                $patientDieInfo = (new PatientInfo())->getInfo($v["patientId"], "liveStatus");
                if ($patientDieInfo["liveStatus"] != "1") {
                    unset($patientList[$k]);
                } else {
                    //计算复诊日期
                    $planVisitDate = date("Y-m-d", strtotime("+" . $visitInfo["remind_count"] . " day"));
                    //判断这个日期是否存在
                    $isExists = ZhyxMongo::getInstance()->setCollection('visit_plan_detail')->findOne(['_id' => new ObjectId($v["id"]), 'plan_list.plan_visit_date' => $planVisitDate]);

                    if (empty($isExists)) {
                        $r = ZhyxMongo::getInstance()->setCollection('visit_plan_detail')->updateOne(['_id' => new ObjectId($v["id"])], ['$push' => [
                            'plan_list' => ['push_status' => 0,
                                'plan_visit_date' => $planVisitDate,
                                'plan_status' => 1,
                                'come_visit_date' => '',
                                'visit_status' => 0]
                        ]]);
                    } else {
                        ZhyxMongo::getInstance()->setCollection('visit_plan_detail')->updateOne(['_id' => new ObjectId($v["id"]), 'plan_list.plan_visit_date' => $planVisitDate], ['$set' => [
                            'plan_list.$.push_status' => 1
                        ]]);
                    }
                }
            }

            $patientIds = array_column($patientList->toArray(), 'patientId');
            $patientNames = array_column($patientList->toArray(), 'patient_name');

            $telephoneArr = array_column($patientList->toArray(), 'presentTelphone');

            # 执行短信的批量发送
            $tubeData = [
                'task_id' => '',
                'template_id' => '',
                'business_id' => $visitId,
                'users' => $patientIds,
                'names' => $patientNames,
                'tubeName' => 'SendSms',
                'task_name' => $visitInfo['visit_name'] ?? "",
                'customer_content' => $visitInfo['period_content'],
                'type' => 4,
                'is_push_wx' => false,
                'source' => 'plan'
            ];

            (PushMessage::getInstance())->send($tubeData, $visitInfo["push_type"]);

            # 判断复诊计划是否存在周期性任务
            if ($visitInfo["period"] !== "") {

                $weekValue = ["1" => "1 week", "2" => "2 week", "3" => "1 month", "4" => "3 month", "5" => "6 month", "6" => "1 year"];

                $visitDate = date("Y-m-d", strtotime("+" . $visitInfo["remind_count"] . " day"));
                $nextVisitTime = date("Y-m-d", strtotime($visitDate . " +" . $weekValue[$visitInfo["period"]]));
                //todo 计算下次日期
                if ($nextVisitTime < $visitInfo["visit_finish_time"]) {


                    //计算推送时间
                    // $delay = strtotime("+ " . $weekValue[$visitInfo["period"]]) - time();
                    $taskTime = date("Y-m-d", strtotime("-" . $visitInfo['remind_count'] . " day", strtotime($nextVisitTime)));

                    # 计算下次复诊时间
                    //$beanstalkdResult = ZhyxBeanstalkd::getInstance()->beansTalk->useTube("sendVisitMessage")->put(json_encode($data, JSON_THROW_ON_ERROR), 0, $delay);
                    //将复诊计划任务投递到任务表中
                    (new TimingTask())->save([
                            'task_name' => '推送复诊计划周期任务-' . $visitInfo["visit_name"],
                            'task_status' => 0,
                            'task_plan_date' => (string)$taskTime,
                            'task_data' => ["visit_id" => $visitId, 'task_name' => $visitInfo["visit_name"], 'tubeName' => "sendVisitMessage"],
                            'deleted_at' => 0,
                            'type' => 'visit_plan'
                        ]
                    );

                    foreach ($patientList as $k => $v) {
                        $isExists = ZhyxMongo::getInstance()->setCollection('visit_plan_detail')->findOne(['_id' => new ObjectId($v["id"]), 'plan_list.plan_visit_date' => $nextVisitTime]);
                        if (empty($isExists)) {
                            $r = ZhyxMongo::getInstance()->setCollection('visit_plan_detail')->updateOne(['_id' => new ObjectId($v["id"])], ['$push' => [
                                'plan_list' => ['push_status' => 0,
                                    'plan_visit_date' => $nextVisitTime,
                                    'plan_status' => 0,
                                    'come_visit_date' => '',
                                    'visit_status' => 0]
                            ]]);
                        }
                    }
                }
            }
            return true;
        } catch (\Exception $exception) {
            \think\facade\Log::error("复诊计划推送失败:" . $exception->getMessage());
            return false;
        }
    }
}